#include "ScanTHos.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <termios.h>
#include <time.h>
#include "serial.h"

int Open_Device(char* devname, int baudrate)
{
    int fd = OpenPort(devname);
    if (fd <= 0) {
        printf("%s serail open failed: %s\n", devname, strerror(errno));
        return -1;
    }

    portinfo_t portinfo = {
        '0',         // print prompt after receiving
        baudrate,    // baudrate: 9600
        '8',         // databit: 8
        '0',         // debug: off
        '0',         // echo: off
        '0',         // flow control: none
        '0',         // parity: none
        '1',         // stopbit: 1
        0            // reserved
    };

    PortSet(fd, &portinfo);
    return fd;
}

int Close_Device(int fd)
{
    return ClosePort(fd);
}

int SerialCanRead(int fd, int timeout)
{
    fd_set fset;
    FD_ZERO(&fset);
    FD_SET(fd, &fset);

    timeval tm;
    tm.tv_sec = timeout / 1000;
    tm.tv_usec = (timeout % 1000) * 1000;

    int ret = select(fd+1, &fset, NULL, NULL, &tm);
    if (ret < 0) {
        printf("receive error: %d, %s\n", fd, strerror(errno));
        return ret;
    } else if (ret == 0) {
        printf("receive timeout: %d, %s\n", fd, strerror(errno));
        return ret;
    }

    return FD_ISSET(fd, &fset);
}

int open_ScanT(int fd, unsigned char* rvdata, int lenl, int timems)
{
    FlushBuffer(fd, 0);
    FlushBuffer(fd, 1);

    char sendCmd[] = {0x16, 0x54, 0x0d, 0x21};

    int ret = PortSend(fd, (const char *)sendCmd, sizeof(sendCmd) / sizeof(sendCmd[0]));
    if (ret == -1) {
        printf("write cmd error!!\n");
        return -1;
    }

    ret = SerialCanRead(fd, timems);
    if (ret > 0) {
        ret = PortRecv(fd, reinterpret_cast<char*>(rvdata), lenl);
    }

    close_ScanT(fd);
    return ret;
}

int close_ScanT(int fd)
{
    FlushBuffer(fd, 0);
    FlushBuffer(fd, 1);

    char sendCmd[] = {0x16, 0x55, 0x0d, 0x21};
    return PortSend(fd, (const char *)sendCmd, sizeof(sendCmd) / sizeof(sendCmd[0]));
}